//
//  ALBaseReqModel.m
//  FanBei
//
//  Created by 哀木涕 on 2016/12/26.
//  Copyright © 2016年 chuxiangkeji. All rights reserved.
//

#import "ALBaseReqModel.h"
#import "ALBaseRespModel.h"

#define OtherLoginMsg @"重新登陆"

@implementation ALBaseReqModel


- (void)get:(void (^)(ALBaseRespModel *respModel))callBack{
    [self request:@"GET" resultCallBack:callBack];
}

- (void)post:(void (^)(ALBaseRespModel *respModel))callBack{
    [self request:@"POST" resultCallBack:callBack];
}


-(void) request:(NSString *)method resultCallBack:(void (^)(ALBaseRespModel *respModel))callBack{
    
    if ([self.requestUrl isEmptyString]) {
        NSException *exception=[[NSException alloc] initWithName:@"缺少请求url" reason:[NSString stringWithFormat:@"%@:url缺失",self] userInfo:nil];
        @throw exception;
    }
     
    NSMutableDictionary *paramsDic= [self mj_keyValuesWithIgnoredKeys:@[@"requestUrl"]];
    paramsDic = [self dealReqData:paramsDic];
    NSError *requestError = nil;
    
    NSString *urlStr = [[MainUrl stringByAppendingString:self.requestUrl] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request= [[AFHTTPRequestSerializer serializer] requestWithMethod:method URLString:urlStr parameters:paramsDic error:&requestError];
    request.timeoutInterval=20.0f;
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",nil];
    [ALProgressHuD show];
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * response, id responseObject, NSError * error) {
        ALBaseRespModel *responModel = [ALBaseRespModel mj_objectWithKeyValues:responseObject];
        if ([responModel.msg rangeOfString:OtherLoginMsg].length) {
            [ALProgressHuD showInfoWithStatus:responModel.msg];
            [[ALSingleTon shareSingTon] cleanUserInfo];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // TODO --- 模态登录界面
            });
        }else{
            if (callBack) {
                callBack(responModel);
                if (error){
                    NSLog(@"错误原因%@",error);
                     [self errorShow:error];
                }else if (responModel.success != 1){
                    [ALProgressHuD showInfoWithStatus:responModel.msg];
                }else{
                    [ALProgressHuD dismiss];
                }
            }
        }
    }] resume];
}
- (NSMutableDictionary *)dealReqData:(NSMutableDictionary *)dict{
    NSMutableArray *array = [NSMutableArray array];
    dict[@"time"] = [NSString GetNowTimes];
//    dict[@"token"] = [ALUserInfo shareInfo].accessToken;
    dict[@"token"] = @"";
    for (NSString *key in dict) {
        NSString *keyvalue = [NSString stringWithFormat:@"%@%@",key,dict[key]];
        [array addObject:keyvalue];
    }
    dict[@"sign"] = [NSString GetSignString:array];
    return dict;
}

//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}
//对返回的错误进行处理
-(void) errorShow:(NSError *)error{
    if(!error) return ;
    NSString *strMsg=nil;
    switch (error.code) {
        case kCFURLErrorBadServerResponse:
            strMsg=@"404异常";
            break;
        case kCFURLErrorTimedOut:
            strMsg=@"请求超时,请检测网络";
            break;
        case kCFURLErrorNotConnectedToInternet:
        case kCFURLErrorCannotConnectToHost:
            strMsg=@"无法连接到远程服务器";
            break;
        default:
            strMsg=@"请求出错了";
            break;
    }
    [ALProgressHuD showInfoWithStatus:strMsg];
    
}


@end
